package com.yuelao.yuelao_backend.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yuelao.yuelao_backend.common.BizException;
import com.yuelao.yuelao_backend.common.ErrorCode;
import com.yuelao.yuelao_backend.dto.GroupDTO;
import com.yuelao.yuelao_backend.entity.Group;
import com.yuelao.yuelao_backend.entity.Group;
import com.yuelao.yuelao_backend.entity.GroupMember;
import com.yuelao.yuelao_backend.mapper.GroupMapper;
import com.yuelao.yuelao_backend.mapper.GroupMemberMapper;
import com.yuelao.yuelao_backend.service.AchievementService;
import com.yuelao.yuelao_backend.service.GroupService;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import jakarta.annotation.Resource;

import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class GroupServiceImpl extends ServiceImpl<GroupMapper, Group> implements GroupService {

    @Resource
    private AchievementService achievementService;
    
    @Resource
    private GroupMemberMapper groupMemberMapper;

    @Override
    public List<GroupDTO> getGroupList() {
        // 实际项目中可能需要分页、筛选等
        List<Group> groups = list();
        return groups.stream()
                .map(this::convertToGroupDTO)
                .collect(Collectors.toList());
    }

    @Override
    public GroupDTO getGroupInfo(Long groupId) {
        Group group = getById(groupId);
        if (group == null) {
            throw new BizException(ErrorCode.NOT_FOUND_ERROR, "群聊不存在");
        }
        return convertToGroupDTO(group);
    }

    @Override
    public String getGroupAnnouncement(Long groupId) {
        Group group = getById(groupId);
        if (group == null) {
            throw new BizException(ErrorCode.NOT_FOUND_ERROR, "群聊不存在");
        }
        return group.getAnnouncement();
    }

    @Override
    @Transactional
    public boolean joinGroup(Long userId, Long groupId) {
        // 检查群组是否存在
        Group group = getById(groupId);
        if (group == null) {
            throw new BizException(ErrorCode.NOT_FOUND_ERROR, "群组不存在");
        }
        
        // 检查群组是否已解散
        if (group.getStatus() != null && group.getStatus() == 0) {
            throw new BizException(ErrorCode.OPERATION_ERROR, "群组已解散");
        }
        
        // 检查是否已加入
        LambdaQueryWrapper<GroupMember> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(GroupMember::getUserId, userId)
               .eq(GroupMember::getGroupId, groupId);
        GroupMember existing = groupMemberMapper.selectOne(wrapper);
        
        if (existing != null) {
            return true; // 已经加入
        }
        
        // 创建群成员记录
        GroupMember member = new GroupMember();
        member.setGroupId(groupId);
        member.setUserId(userId);
        member.setRole("member");
        member.setJoinedAt(LocalDateTime.now());
        member.setUpdatedAt(LocalDateTime.now());
        boolean saved = groupMemberMapper.insert(member) > 0;
        
        if (saved) {
            // 更新群组成员数
            group.setMemberCount((group.getMemberCount() != null ? group.getMemberCount() : 0) + 1);
            updateById(group);
            
            // 检查群组相关成就
            achievementService.checkGroupAchievements(userId);
        }
        
        return saved;
    }

    @Override
    public GroupDTO convertToGroupDTO(Group group) {
        if (group == null) {
            return null;
        }
        GroupDTO dto = new GroupDTO();
        BeanUtils.copyProperties(group, dto);
        return dto;
    }
}